package com.neusoft.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.neusoft.entity.Operator;
import com.neusoft.service.OperatorService;

@Controller
@RequestMapping("/operator")
public class OperatorController {
	@Autowired
	OperatorService operatorService;

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request, String account, String password) {
		ModelAndView modelAndView = new ModelAndView();
		Operator operator = operatorService.loadListByExample(account, password).get(0); ///// get(0)?????
		if (operator != null) {
			modelAndView.addObject("loginMessage", "登录成功！");
			modelAndView.addObject("operator", operator);
			modelAndView.setViewName("operator/borrows");
			request.getSession().setAttribute("operator", operator);
		} else {
			modelAndView.addObject("loginMessage", "登录失败！");
			modelAndView.setViewName("operator/login");
		}
		return modelAndView;
	}

	@RequestMapping("/getInformation")
	public ModelAndView getInformation(Integer ID) {
		ModelAndView modelAndView = new ModelAndView("operator/operatorinformation");
		Operator operator = operatorService.loadOperatorById(ID);
		modelAndView.addObject("operator", operator);
		return modelAndView;
	}

	@RequestMapping("/modifyPassword")
	public ModelAndView modifyPassword(HttpServletRequest request, String oldPassword, String newPassword,
			String confirm) {
		ModelAndView modelAndView = new ModelAndView("operator/operatorinformation");
		if (oldPassword == null || newPassword == null || confirm == null || oldPassword.trim().isEmpty()
				|| newPassword.trim().isEmpty() || confirm.trim().isEmpty()) {
			modelAndView.addObject("errorMess", "密码不能为空，修改密码失败!");
		} else if (!newPassword.equals(confirm)) {
			modelAndView.addObject("errorMess", "新密码和确认密码不一致，修改密码失败！");
		} else {
			modelAndView.addObject("successMess", "修改成功！");
			Operator operator = (Operator) request.getSession().getAttribute("operator");
			operator.setoPassword(newPassword);
			operatorService.updateOperatorByIdSelective(operator);
			request.getSession().setAttribute("operator", operator); // 同个operator吗???????????????
		}
		return modelAndView;
	}

	@RequestMapping("/updateOperator")
	public ModelAndView updateOperator(Operator operator) {
		ModelAndView modelAndView = new ModelAndView("operator/operatorinformation");
		operatorService.updateOperatorByIdSelective(operator);
		modelAndView.addObject("operator", operator);
		return modelAndView;
	}
}
